#!/usr/bin/env python
# coding=utf-8
#本页为预测任务
#type=1 实时任务 type=2 预测任务
import Queue
import threading
import time
from weather import weatherApi
weather=weatherApi()
queue = Queue.Queue()
is_ready=threading.Semaphore(1)
class ThreadUrl(threading.Thread):


    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue


    def run(self):
        while True:
            try:
                city= self.queue.get()
                cityid=city[0]
                accu_cityid=city[1]
                print  cityid
                forecast_result=[]
                for num in range(1,16):

                    forecast_result.append(weather.getForecast(accu_cityid,num))
                is_ready.acquire()
                id=weather.is_exist(cityid,weather.getDate())

                if id:
                    weather.update_forecast(id,forecast_result)
                else :
                    weather.insert_forecast(cityid,forecast_result)
                is_ready.release()
                self.queue.task_done()
            except Exception as e:
                pass


def main():

    for i in range(1,15):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()
    while(True):
        try:
             if weather.getTask(2) :
                time.sleep(5)
                citylist=weather.getCity()
                for city in  citylist:
                    queue.put(city)
             time.sleep(60)
        except Exception as e:
            pass
    queue.join()

main()
